<template>
    <h1>水果管理</h1>
    <p>
        <button @click="onadd">新增水果</button>
    </p>
    <ul>
        <li  v-for="item in sg" :key="item.id">
        {{ item.id }} ------- {{ item.name }} ------- {{ "$" + item.price.toFixed(2) }}
        <button @click="ondel(item.id)">删除</button>
        <button @click="onedit(item.id)">修改</button>
        </li>
    </ul>
    
</template>

<script>
    export default {
        data(){
            return {
                sg:[
                    {id:1 , name:'苹果' , price:5},
                    {id:2 , name:'香蕉' , price:3},
                    {id:3 , name:'草莓' , price:4},
                    {id:4 , name:'西瓜' , price:2},
                    {id:5 , name:'柠檬' , price:3},
                ]
            }
        },
        methods:{
            onadd(){
               this.sg.push({id:this.sg.length+1, name:prompt('请输入水果名称：'), 
               price:parseFloat(prompt('请输入水果价格：'))
                })
            },
            ondel(id){
                if(confirm('确认删除该水果吗？')){
                    this.sg = this.sg.filter(item => item.id!== id)
                }
                
            },
            onedit(id){
                this.sg = this.sg.map(item => {
                    if(item.id === id){
                        item.name = prompt('请输入水果名称：',item.name) || item.name;
                        item.price = parseFloat(prompt('请输入水果价格：',item.price) || item.price);
                    }
                    return item
                }) 
            },
        }
    }
</script>